package com.wlr.study.juc;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author lerong.wang
 * @version 1.0.0
 * @description
 * @date 2025/5/28 13:48
 */
public class ArrayBlockingQueueTest {

    public static void main(String[] args) {
        ReentrantLock reentrantLock = new ReentrantLock(true);
        reentrantLock.lock();
        // 创建容量为5的ArrayBlockingQueue
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(5);

        // 生产者线程
        Thread producer = new Thread(() -> {
            try {
                for (int i = 1; i <= 10; i++) {
                    queue.put(i); // 如果队列满，会阻塞等待
                    System.out.println("生产者放入: " + i + "，队列大小: " + queue.size());
                    Thread.sleep(200); // 模拟生产耗时
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        // 消费者线程
        Thread consumer = new Thread(() -> {
            try {
                for (int i = 1; i <= 10; i++) {
                    Integer item = queue.take(); // 如果队列空，会阻塞等待
                    System.out.println("消费者取出: " + item + "，队列大小: " + queue.size());
                    Thread.sleep(100); // 模拟消费耗时
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producer.start();
        consumer.start();
    }

}